﻿using Raven;
using UnityEngine;
using Vector2 = Raven.Vector2;

public class RocketDisplay : UnityDisplayObject
{
    private ProjectileRocket _projectileRocket;
    private GameObject _cycleObject;

    public RocketDisplay(BaseGameEntity entity) : base(entity)
    {
        _projectileRocket = entity as ProjectileRocket;
    }

    public override void Start()
    {
        base.Start();

        Vector2 pos = _owner.Pos();
        _gameObject.transform.position = new Vector3((float)pos.x, (float)pos.y);
        _gameObject.AddComponent<MeshFilter>().mesh =
            MeshFactory.EllipseMesh(Vector3.zero, 2, Color.yellow);
        MeshRenderer render = _gameObject.AddComponent<MeshRenderer>();
        render.material = new Material(Shader.Find("Sprites/Default"));
    }


    public override void Update()
    {
        Vector2 pos = _owner.Pos();
        _gameObject.transform.position = new Vector3((float)pos.x, (float)pos.y);

        if (_projectileRocket.HasImpacted())
        {
            if (_cycleObject == null)
            {
                Mesh cycleMesh =
                    MeshFactory.CycleMesh(Vector3.zero, (float)_projectileRocket.CurrentBlastRadius(), Color.yellow);
                _cycleObject = new GameObject("cycle");
                _cycleObject.AddComponent<MeshFilter>().mesh = cycleMesh;
                MeshRenderer render = _cycleObject.AddComponent<MeshRenderer>();
                render.material = new Material(Shader.Find("Sprites/Default"));
                _cycleObject.transform.SetParent(_gameObject.transform, false);
            }
            else
            {
                VertexBuffer vb = VertexBuffer.Begin();
                vb.vertexColor = Color.yellow;
                vb.AddCycle(Vector3.zero, (float)_projectileRocket.CurrentBlastRadius());
                _cycleObject.GetComponent<MeshFilter>().mesh.SetVertices(vb.vertices);
                vb.End();
            }
        }
    }
}